<template>
  <div id="product-home">
    <Navbar />
    <div class="search-category-container">
      <div class="search-box">
        <input type="text" v-model="searchQuery" placeholder="搜索商品..." @keyup.enter="filterProducts" />
        <button @click="filterProducts">搜索</button>
      </div>

      <div class="category-nav">
        <span class="category-title">商品分类：</span>
        <ul class="category-list">
          <li v-for="category in categories" :key="category.id" :class="{ active: selectedCategory === category.id }"
            @click="selectCategory(category.id)">
            {{ category.name }}
          </li>
        </ul>
      </div>
    </div>

    <div class="product-list-container">
      <van-swipe class="swiper-container" :autoplay="5000" indicator-color="#e05649" ref="swipeRef" @change="onSwipeChange">
        <van-swipe-item v-for="(item, index) in swiperList" :key="item.id" >
          <img v-lazy="item" class="swiper-image"  @error="handleImageError(index)" />
        </van-swipe-item>
      </van-swipe>
      <div class="swipe-controls">
        <button class="swipe-prev" @click="prevSlide":disabled="currentIndex === 0">❮</button>
        <button class="swipe-next" @click="nextSlide">❯</button>
      </div>


      <div class="product-list">
        <div class="product-item" v-for="(product, index) in filteredProducts" :key="product.id"
          @click="goToDetail(product.id)">
          <div class="product-img">
            <img :src="product.image_url" alt="product" class="product-image" />
          </div>
          <div class="product-info">
            <span class="product-name">{{ product.name }}</span>
            <span class="product-price">¥{{ product.price }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
  <footer class="footer-links">
      <div class="link-group">
        <a>关于校麦</a>
        <a>协议及隐私权政策</a>
        <a>廉正举报</a>
        <a>联系合作</a>
      </div>
      <div class="link-group">
        <a>招聘信息</a>
        <a>防骗秘籍</a>
        <a>商户入驻</a>
      </div>
      <div class="copyright">© 2025-2025 校麦网</div>
    </footer>
  <LoginDialog v-if="showLoginDialog" @close="showLoginDialog = false" />
  <RegisterDialog v-if="showRegisterDialog" @close="showRegisterDialog = false" />
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import LoginDialog from "../../components/LoginDialog.vue";
import RegisterDialog from "../../components/RegisterDialog.vue";
import { Swipe, SwipeItem } from 'vant';
import Navbar from "../../components/Navbar.vue";
import 'vant/lib/index.css';
import 'vant/lib/swipe/index.css';


const router = useRouter();
const showLoginDialog = ref(false);
const showRegisterDialog = ref(false);
const isLoggedIn = ref(localStorage.getItem("isLoggedIn") === "true");


// 轮播图数据
const swiperList = ref([
   "../public/69783cad-a809-44cd-abe8-1212d30877e6.jpg" ,
   "../public/881072d3-877a-471d-809a-30b174ccc257.jpg" ,
   "../public/d038f920-0f4a-47df-b149-e316e175eb9d.jpg" ,
   "../public/de193245-14cb-4a02-b2d6-dc63e44c6202.jpg" 
]);


const products = ref([]);
const categories = ref([
  { id: 0, name: '全部' },
  { id: 1, name: '食品' },
  { id: 2, name: '娱乐' },
  { id: 3, name: '物品' },
  { id: 4, name: '电子产品' },
  { id: 5, name: '服装鞋帽' }
]);
const searchQuery = ref('');
const selectedCategory = ref(0);
const handleImageError = (index) => {
  swiperList.value[index].image_url = '/default-banner.jpg';
};
const loadData = async () => {
  try {
    const response = await fetch('http://localhost:3000/products');
    products.value = await response.json();
    console.log("加载商品数据成功:", products.value);
  } catch (error) {
    console.error('加载数据失败:', error);
  }
};

const filteredProducts = computed(() => {
  return products.value.filter(product => {
    const categoryName = categories.value.find(c => c.id === selectedCategory.value)?.name;
    const isCategoryMatch = categoryName === '全部' || product.type === categoryName;
    const isSearchMatch = product.name.toLowerCase().includes(searchQuery.value.toLowerCase());
    return isCategoryMatch && isSearchMatch;
  });
});

const goToDetail = (productId) => {
  router.push({ name: 'ProductDetail', params: { id: productId } });
};

const swipeRef = ref(null);
const currentIndex = ref(0);
const onSwipeChange = (index) => {
  currentIndex.value = index;
};

const prevSlide = () => {
  if (swipeRef.value) {
    swipeRef.value.prev();
  }
};

const nextSlide = () => {
  if (swipeRef.value) {
    swipeRef.value.next();
  }
};
watch(swiperList, () => {
  if (swipeRef.value) {
    swipeRef.value.refresh(); // 刷新轮播图
  }
});
const selectCategory = (categoryId) => (selectedCategory.value = categoryId);
const filterProducts = () => { };
watch(selectedCategory, () => (searchQuery.value = ''));

onMounted(() => {
  loadData();
});

watch(() => router.currentRoute.value, () => {
  loadData();
});
</script>

<style scoped>
.search-category-container {
  padding: 20px;
  background: #fff;
  /* border-bottom: 1px solid #eee; */
  display: flex;
  justify-content: space-around;
  align-items: center;
  /* box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); */
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-box input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 300px;
}

.search-box button {
  padding: 8px 16px;
  background: #e05649;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  color: #fff;
}

.category-nav {
  display: flex;
  align-items: center;
  gap: 10px;
}

.category-title {
  font-weight: bold;
}

.category-list {
  display: flex;
  gap: 20px;
  list-style: none;
  padding: 0;
  margin: 0;
}

.category-list li {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.category-list li:hover {
  background: #f0f0f0;
}

.category-list li.active {
  background: #e05649;
  color: white;
}

* {
  /* margin: 0 auto; */
  padding: 0;
}

#app {
  width: 100%;
  height: auto;
  margin: 0;
  padding-top: 0;
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #ffffff;
}

.product-list-container {
  padding: 20px;
  display: grid;
  justify-content: center;
  justify-items: center;
  /* background-color: #f2f2f2; */
  width: 100%;
  height: auto;
}

.product-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top:20px;
  min-height: 400px;
}

.product-item {
  width: 200px;
  height: 250px;
  border: 1px solid #ccc;
  padding: 10px;
  cursor: pointer;
  text-align: center;
  background-color: #fff;
  border-radius: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin: 3px 3px 3px 3px;
}

.product-item:hover{
  border: 1px solid #e05649;
}

.product-img{
  width: 180px;
  height: 200px;
  align-self: center;
  overflow: hidden;
}
.product-image {
  width: 100%;
  height: 100%;
  border-radius: 20px;
  object-fit: cover;
}

.product-info {
  margin-top: 10px;
    display: flex;
    justify-content: center;
    flex-direction: column;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
}

.product-price {
  color: #e05649;
}

.top-navbar {
  display: flex;
  justify-content: space-between;
  gap: 20vh;
  background-color: #e05649;
  padding: 10px;
  position: relative;
  z-index: 100px;
  transition: all 0.3s ease;
}

.back {
  display: flex;
  justify-content: start;
  color: #fff;
}

.nav-right {
  display: flex;
  align-content: flex-end;
}

.nav-link:hover {
  color: rgb(130, 69, 25);
  /* background-color: #333; */
  border-radius: 20%;
}

.fixed {
  position: sticky;
  top: 0;
  width: 100%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.nav-link {
  margin-right: 20px;
  text-decoration: none;
  color: rgb(255, 255, 255);
}

.sign-in-button,
.register-button,
.sign-out-button {
  background-color: #e05649;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
}

.swiper-container {
  /* padding: 10px; */
  background: #fff;
  border-bottom: 2px solid #e05649;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  position: relative;
}

.swiper-image {
  width:1000px;
  height: 400px;
  object-fit: cover;
  border-radius: 12px;
}
@media (max-width: 768px) {
  .swiper-image {
    height: 150px;
  }
  
  .swipe-controls {
    padding: 0 10px;
  }
  
  .swipe-prev, .swipe-next {
    padding: 8px 12px;
  }
}
/* 调整下方商品列表的间距 */
/* .product-list-container {
  margin-top: -20px;
} */

.van-swipe__indicator {
  width: 8px;
  height: 8px;
  background: rgba(255, 255, 255, 0.5);
}

.van-swipe__indicator--active {
  background: #e05649;
}

.swipe-controls {
  position: absolute;
  top: 50%;
  width: 100%;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  transform: translateY(-50%);
  pointer-events: none;
  z-index: 10;
}

.swipe-prev, .swipe-next {
  position: relative;
  pointer-events: auto;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s;
  z-index: 11;
}

.swipe-prev:hover, .swipe-next:hover {
  background: rgba(0, 0, 0, 0.7);
}


.swiper-container {
  position: relative;
  /* padding: 20px 40px; */
  padding: 1px 2px;
}

.van-swipe-item {
  transition: transform 0.5s ease;
}

.footer-links[data-v-9e307265] {
    border-top: 1px solid #eee;
    padding: 30px;
    text-align: center;
    margin-left: 260px;
}
footer {
    display: block;
    unicode-bidi: isolate;
    background-color: #f2f2f2;
}

.link-group {
  margin-bottom: 12px;
}

.link-group a {
  color: #999;
  font-size: 12px;
  margin: 0 12px;
  cursor: pointer;
}

.link-group a:hover {
  color: #230303;
}
</style>